import { Form, Upload, Icon, message } from 'antd';
import React, { useState } from 'react';
import uploader from '../../utils/upload';

export default props => {
  const { title, onUploaded, initialValue } = props
  const [upLoading, setUpLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState(initialValue);

  const onPrepare = file => {
    const {err, msg, res} = uploader.do(file, url => {
      setImageUrl(url);

      onUploaded && onUploaded(url);
    });

    if (err) {
      message.error(msg);
      return;
    }

    return res;
  };

  const onChange = info => setUpLoading(info.file.status !== 'done');

  return (
    <Form.Item label={title || "上传logo"} labelCol={{ span: 5 }} wrapperCol={{ span: 15 }}>
      <Upload
          name="avatar"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          beforeUpload={onPrepare}
          onChange={onChange}
        >
          {
            imageUrl ? 
            <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> 
            : 
            <div>
              <Icon type={upLoading ? 'loading' : 'plus'} />
              <div className="ant-upload-text">Upload</div>
            </div>
          }
      </Upload>
    </Form.Item>
  );
}